<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-form-item label="农场编号" prop="farmNo">
        <el-input v-model="formData.farmNo" placeholder="请输入农场编号" :disabled="isView" />
      </el-form-item>
      <el-form-item label="农场名称" prop="farmName">
        <el-input v-model="formData.farmName" placeholder="请输入农场名称" :disabled="isView" />
      </el-form-item>
      <el-form-item label="农场分类" prop="categoryId">
        <el-input
          v-model="selectedCategoryName"
          placeholder="请选择农场分类"
          clearable
          readonly
          :disabled="isView"
          @clear="handleClearCategory"
        >
          <template #suffix>
            <Icon
              v-if="!isView"
              icon="ep:search"
              class="cursor-pointer hover:text-primary"
              @click="openCategoryDialog"
            />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="地址" prop="areaPath">
        <el-cascader
          v-model="areaPath"
          :options="areaList"
          :props="cascaderProps"
          clearable
          filterable
          placeholder="请选择省/市/区/镇"
          @change="handleAreaChange"
          :disabled="isView"
          class="!w-1/1"
        />
        <el-button
          v-if="formData.province && !isView"
          type="primary"
          link
          @click="locateByAddress"
          class="ml-2"
        >
          📍 根据地址定位地图
        </el-button>
      </el-form-item>
      <el-form-item label="详细门牌号地址" prop="detailAddress">
        <el-input v-model="formData.detailAddress" placeholder="请输入详细门牌号地址" :disabled="isView" />
      </el-form-item>
      <el-form-item label="地图定位">
        <el-alert v-if="!isView" title="使用提示" type="info" :closable="false" class="mb-2">
          <template #default>
            <div class="text-sm">
              <p
                >📍 <strong>方式一：搜索地址</strong> -
                在下方输入框中输入详细地址（如：北京市朝阳区xxx街道xxx号）</p
              >
              <p>🖱️ <strong>方式二：点击地图</strong> - 直接在地图上点击选择位置</p>
              <p>💡 搜索建议：请输入完整地址，包含省市区等信息，这样更容易找到准确位置</p>
            </div>
          </template>
        </el-alert>
        <Map
          ref="mapRef"
          :isWrite="!isView"
          :clickMap="!isView"
          :center="mapCenter"
          @locate-change="handleLocationChange"
        />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude">
            <el-input v-model="formData.longitude" placeholder="自动获取" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="formData.latitude" placeholder="自动获取" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="负责人姓名" prop="managerName">
        <el-input v-model="formData.managerName" placeholder="请输入负责人姓名" :disabled="isView" />
      </el-form-item>
      <el-form-item label="负责人联系方式" prop="managerPhone">
        <el-input v-model="formData.managerPhone" placeholder="请输入负责人联系方式" :disabled="isView" />
      </el-form-item>
      <el-form-item label="负责人身份证号" prop="managerIdCard">
        <el-input v-model="formData.managerIdCard" placeholder="请输入负责人身份证号" :disabled="isView" />
      </el-form-item>
      <el-form-item label="农场面积（亩）" prop="farmArea">
        <el-input v-model="formData.farmArea" placeholder="请输入农场面积（亩）" :disabled="isView" />
      </el-form-item>
      <el-form-item label="种植产物" prop="plantProductIds">
        <el-select
          v-model="formData.plantProductIds"
          multiple
          placeholder="请选择种植产物"
          :disabled="isView"
          style="width: 100%"
          collapse-tags
          collapse-tags-tooltip
        >
          <el-option
            v-for="item in plantProductList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="农场资质文件" prop="qualificationFiles">
        <UploadFile
          v-model="formData.qualificationFiles"
          :file-type="['jpg', 'jpeg', 'png', 'pdf']"
          :file-size="10"
          :limit="5"
          directory="farm"
          :disabled="isView"
        />
        <div class="text-xs text-gray-400 mt-1">
          支持上传图片（jpg、png）或PDF文件，单个文件不超过10MB，最多上传5个文件
        </div>
      </el-form-item>
      <el-form-item label="农场背景简介" prop="backgroundIntro">
        <Editor v-model="formData.backgroundIntro" :height="400" :editor-config="editorConfig" :disabled="isView" />
      </el-form-item>
      <el-form-item label="关联用户" prop="userId">
        <!-- 隐藏的input用于表单验证 -->
        <el-input v-model="formData.userId" v-show="false" />
        <!-- 显示的input用于展示用户名称 -->
        <el-input
          v-model="selectedUserName"
          placeholder="请选择关联的农场用户"
          clearable
          readonly
          :disabled="isView"
          @clear="handleClearUser"
        >
          <template #suffix>
            <Icon
              v-if="!isView"
              icon="ep:search"
              class="cursor-pointer hover:text-primary"
              @click="openUserDialog"
            />
          </template>
        </el-input>
        <div class="text-xs text-gray-400 mt-1"> 选择一个已有的农场角色用户，关联到此农场 </div>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态" :disabled="isView">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.FARM_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="formData.auditStatus" placeholder="请选择审核状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.AUDIT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核备注" prop="auditRemark">
        <el-input v-model="formData.auditRemark" placeholder="请输入审核备注" />
      </el-form-item>
      <el-form-item label="审核时间" prop="auditTime">
        <el-date-picker
          v-model="formData.auditTime"
          type="date"
          value-format="x"
          placeholder="选择审核时间"
        />
      </el-form-item>
      <el-form-item label="审核人" prop="auditUser">
        <el-input v-model="formData.auditUser" placeholder="请输入审核人" />
      </el-form-item> -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" :disabled="isView" />
      </el-form-item>

      <!-- 违规记录列表（仅查看模式显示） -->
      <el-form-item v-if="isView && violationRecordList.length > 0" label="违规记录">
        <el-table
          :data="violationRecordList"
          border
          style="width: 100%"
          max-height="300"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="违规时间" prop="violationTime" width="180" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.violationTime) }}
            </template>
          </el-table-column>
          <el-table-column label="违规原因" prop="violationReason" show-overflow-tooltip />
        </el-table>
      </el-form-item>
      <el-form-item v-if="isView && violationRecordList.length === 0" label="违规记录">
        <el-empty description="暂无违规记录" :image-size="100" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button v-if="!isView" @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">{{ isView ? '关 闭' : '取 消' }}</el-button>
    </template>
  </Dialog>

  <!-- 分类选择弹窗 -->
  <CategorySelectDialog ref="categoryDialogRef" @confirm="handleCategoryConfirm" />

  <!-- 用户选择弹窗 -->
  <UserSelectDialog ref="userDialogRef" @confirm="handleUserConfirm" />
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { InfoApi, InfoVO } from '@/api/farm/info'
import { ViolationRecordApi, ViolationRecordVO } from '@/api/farm/violationrecord'
import CategorySelectDialog from './CategorySelectDialog.vue'
import UserSelectDialog from './UserSelectDialog.vue'
import type { CategoryVO } from '@/api/farm/category'
import type { UserVO } from '@/api/system/user'
import * as AreaApi from '@/api/system/area'
import Map from '@/components/Map/index.vue'
import { UploadFile } from '@/components/UploadFile'
import { Editor } from '@/components/Editor'
import type { IEditorConfig } from '@wangeditor/editor'
import { getUploadUrl } from '@/components/UploadFile/src/useUpload'
import { getRefreshToken, getTenantId } from '@/utils/auth'
import { formatDate } from '@/utils/formatTime'

/** 农场信息 表单 */
defineOptions({ name: 'InfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；view - 查看
const isView = computed(() => formType.value === 'view') // 是否为查看模式
const formData = ref({
  id: undefined,
  farmNo: undefined,
  farmName: undefined,
  categoryId: undefined as number | undefined,
  categoryCode: undefined as string | undefined,
  userId: undefined as number | undefined,
  province: undefined as string | undefined,
  city: undefined as string | undefined,
  district: undefined as string | undefined,
  town: undefined as string | undefined,
  detailAddress: undefined,
  longitude: undefined as number | undefined,
  latitude: undefined as number | undefined,
  managerName: undefined,
  managerPhone: undefined,
  managerIdCard: undefined,
  farmArea: undefined,
  plantProductIds: [] as string[],
  qualificationFiles: '',
  backgroundIntro: '',
  loginName: undefined,
  password: undefined,
  defaultPassword: undefined,
  status: undefined,
  auditStatus: undefined,
  auditRemark: undefined,
  auditTime: undefined,
  auditUser: undefined,
  remark: undefined
})
const formRules = reactive({
  farmNo: [{ required: true, message: '农场编号不能为空', trigger: 'blur' }],
  farmName: [{ required: true, message: '农场名称不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '农场分类ID不能为空', trigger: 'change' }],
  categoryCode: [{ required: true, message: '农场分类编码不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '请选择关联用户', trigger: 'change' }],
  managerName: [{ required: true, message: '负责人姓名不能为空', trigger: 'blur' }],
  managerPhone: [{ required: true, message: '负责人联系方式不能为空', trigger: 'blur' }],
  plantProductIds: [{ required: true, message: '请选择种植产物', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const categoryDialogRef = ref() // 分类选择弹窗
const userDialogRef = ref() // 用户选择弹窗
const selectedCategoryName = ref('') // 选中的分类名称
const selectedUserName = ref('') // 选中的用户名称
const areaList = ref<any[]>([]) // 地区列表
const areaPath = ref<number[]>([]) // 地区选择路径
const mapRef = ref() // 地图组件引用
const mapCenter = ref('') // 地图中心点（经度,纬度）
const violationRecordList = ref<ViolationRecordVO[]>([]) // 违规记录列表
const cascaderProps = {
  children: 'children',
  label: 'name',
  value: 'id',
  isLeaf: 'leaf',
  emitPath: true // 返回完整路径数组
}

// 虚拟种植产物数据
const plantProductList = ref([
  { id: '1', name: '西红柿' },
  { id: '2', name: '黄瓜' },
  { id: '3', name: '白菜' },
  { id: '4', name: '萝卜' },
  { id: '5', name: '茄子' },
  { id: '6', name: '辣椒' },
  { id: '7', name: '土豆' },
  { id: '8', name: '玉米' },
  { id: '9', name: '小麦' },
  { id: '10', name: '水稻' },
  { id: '11', name: '苹果' },
  { id: '12', name: '梨' },
  { id: '13', name: '桃子' },
  { id: '14', name: '葡萄' },
  { id: '15', name: '草莓' }
])

// 富文本编辑器配置
const editorConfig: Partial<IEditorConfig> = {
  placeholder: '请输入农场背景简介...',
  MENU_CONF: {
    uploadImage: {
      server: getUploadUrl(),
      maxFileSize: 5 * 1024 * 1024, // 5MB
      maxNumberOfFiles: 10,
      allowedFileTypes: ['image/*'],
      headers: {
        Accept: '*',
        Authorization: 'Bearer ' + getRefreshToken(),
        'tenant-id': getTenantId()
      },
      timeout: 15 * 1000,
      fieldName: 'file',
      meta: {
        directory: 'farm'
      },
      metaWithUrl: true,
      onBeforeUpload(file: File) {
        return file
      },
      onSuccess(file: File, res: any) {
        console.log('图片上传成功', file, res)
      },
      onFailed(file: File, res: any) {
        console.error('图片上传失败', file, res)
      },
      onError(file: File, err: any, res: any) {
        console.error('图片上传错误', file, err, res)
      },
      customInsert(res: any, insertFn: any) {
        insertFn(res.data, 'image', res.data)
      }
    },
    uploadVideo: {
      server: getUploadUrl(),
      maxFileSize: 50 * 1024 * 1024, // 50MB
      maxNumberOfFiles: 5,
      allowedFileTypes: ['video/*'],
      headers: {
        Accept: '*',
        Authorization: 'Bearer ' + getRefreshToken(),
        'tenant-id': getTenantId()
      },
      timeout: 60 * 1000, // 60秒，视频文件较大需要更长时间
      fieldName: 'file',
      meta: {
        directory: 'farm'
      },
      metaWithUrl: true,
      onBeforeUpload(file: File) {
        console.log('开始上传视频', file)
        return file
      },
      onProgress(progress: number) {
        console.log('视频上传进度', progress)
      },
      onSuccess(file: File, res: any) {
        console.log('视频上传成功', file, res)
      },
      onFailed(file: File, res: any) {
        console.error('视频上传失败', file, res)
      },
      onError(file: File, err: any, res: any) {
        console.error('视频上传错误', file, err, res)
      },
      customInsert(res: any, insertFn: any) {
        insertFn(res.data, 'video', res.data)
      }
    }
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 加载地区列表
  if (areaList.value.length === 0) {
    areaList.value = await AreaApi.getAreaTree()
  }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await InfoApi.getInfo(id)

      // 确保资质文件字段是字符串类型（可能后端返回null或undefined）
      if (!formData.value.qualificationFiles) {
        formData.value.qualificationFiles = ''
      }
      // 确保背景简介是字符串类型
      if (!formData.value.backgroundIntro) {
        formData.value.backgroundIntro = ''
      }

      // 如果有分类ID，需要加载分类信息以显示名称
      if (formData.value.categoryId) {
        await loadCategoryName(formData.value.categoryId)
      }
      // 如果有用户ID，需要加载用户信息以显示名称
      if (formData.value.userId) {
        await loadUserName(formData.value.userId)
      }
      // 如果有地区信息，需要构建地区路径用于显示
      if (formData.value.province) {
        buildAreaPath()
      }
      // 如果有经纬度，设置地图中心点
      if (formData.value.longitude && formData.value.latitude) {
        mapCenter.value = `${formData.value.longitude},${formData.value.latitude}`
        // 延迟调用地图定位，确保地图组件已渲染
        nextTick(() => {
          mapRef.value?.regeoCode(mapCenter.value)
        })
      }

      // 如果是查看模式，加载违规记录列表
      if (type === 'view') {
        await loadViolationRecords(id)
      }
    } finally {
      formLoading.value = false
    }
  }
}

/** 加载分类名称 */
const loadCategoryName = async (categoryId: number) => {
  try {
    const { CategoryApi } = await import('@/api/farm/category')
    const category = await CategoryApi.getCategory(categoryId)
    selectedCategoryName.value = category.categoryName
  } catch (error) {
    console.error('加载分类信息失败:', error)
  }
}

/** 加载用户名称 */
const loadUserName = async (userId: number) => {
  try {
    const { getUser } = await import('@/api/system/user')
    const user = await getUser(userId)
    selectedUserName.value = `${user.nickname || user.username} (${user.username})`
  } catch (error) {
    console.error('加载用户信息失败:', error)
  }
}

/** 加载违规记录列表 */
const loadViolationRecords = async (farmId: number) => {
  try {
    const list = await ViolationRecordApi.getViolationRecordListByFarmId(farmId)
    violationRecordList.value = list || []
  } catch (error) {
    console.error('加载违规记录失败:', error)
    violationRecordList.value = []
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as InfoVO

    // 处理资质文件：如果是数组，转换为逗号分隔的字符串
    if (Array.isArray(data.qualificationFiles)) {
      data.qualificationFiles = data.qualificationFiles.join(',')
    }

    if (formType.value === 'create') {
      await InfoApi.createInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await InfoApi.updateInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    farmNo: undefined,
    farmName: undefined,
    categoryId: undefined as number | undefined,
    categoryCode: undefined as string | undefined,
    userId: undefined as number | undefined,
    province: undefined as string | undefined,
    city: undefined as string | undefined,
    district: undefined as string | undefined,
    town: undefined as string | undefined,
    detailAddress: undefined,
    longitude: undefined as number | undefined,
    latitude: undefined as number | undefined,
    managerName: undefined,
    managerPhone: undefined,
    managerIdCard: undefined,
    farmArea: undefined,
    plantProductIds: [] as string[],
    qualificationFiles: '',
    backgroundIntro: '',
    loginName: undefined,
    password: undefined,
    defaultPassword: undefined,
    status: undefined,
    auditStatus: undefined,
    auditRemark: undefined,
    auditTime: undefined,
    auditUser: undefined,
    remark: undefined
  }
  selectedCategoryName.value = '' // 清空分类名称
  selectedUserName.value = '' // 清空用户名称
  areaPath.value = [] as number[] // 清空地区路径
  mapCenter.value = '' // 清空地图中心点
  violationRecordList.value = [] // 清空违规记录列表
  formRef.value?.resetFields()
}

/** 打开分类选择弹窗 */
const openCategoryDialog = () => {
  categoryDialogRef.value?.open()
}

/** 分类选择确认 */
const handleCategoryConfirm = (category: CategoryVO) => {
  formData.value.categoryId = category.id
  formData.value.categoryCode = category.categoryCode
  selectedCategoryName.value = category.categoryName
}

/** 清空分类选择 */
const handleClearCategory = () => {
  formData.value.categoryId = undefined
  formData.value.categoryCode = undefined
  selectedCategoryName.value = ''
}

/** 打开用户选择弹窗 */
const openUserDialog = () => {
  // 这里可以传入农场角色的ID，需要根据实际情况配置
  // 如果知道农场角色的具体ID，可以传入，否则在后端筛选
  userDialogRef.value?.open()
}

/** 用户选择确认 */
const handleUserConfirm = (user: UserVO) => {
  formData.value.userId = user.id
  selectedUserName.value = `${user.nickname || user.username} (${user.username})`
  // 触发表单验证，清除错误提示
  nextTick(() => {
    formRef.value?.validateField('userId')
  })
}

/** 清空用户选择 */
const handleClearUser = () => {
  formData.value.userId = undefined
  selectedUserName.value = ''
  // 触发表单验证，显示错误提示
  nextTick(() => {
    formRef.value?.validateField('userId')
  })
}

/** 地区选择改变 */
const handleAreaChange = (value: any[]) => {
  if (!value || value.length === 0) {
    // 清空地区信息
    formData.value.province = undefined
    formData.value.city = undefined
    formData.value.district = undefined
    formData.value.town = undefined
    return
  }

  // 根据选择的路径，从地区树中找到对应的名称
  const names = getAreaNames(value)

  // 根据选择的层级，分别赋值
  formData.value.province = names[0] || undefined
  formData.value.city = names[1] || undefined
  formData.value.district = names[2] || undefined
  formData.value.town = names[3] || undefined
}

/** 根据ID路径获取地区名称 */
const getAreaNames = (idPath: number[]): string[] => {
  const names: string[] = []
  let currentList = areaList.value

  for (const id of idPath) {
    const node = currentList.find((item: any) => item.id === id)
    if (node) {
      names.push(node.name)
      currentList = node.children || []
    } else {
      break
    }
  }

  return names
}

/** 构建地区路径（用于编辑时回显） */
const buildAreaPath = () => {
  const { province, city, district, town } = formData.value
  if (!province) {
    areaPath.value = []
    return
  }

  const path: number[] = []
  let currentList = areaList.value

  // 查找省份
  const provinceNode = currentList.find((item: any) => item.name === province)
  if (provinceNode) {
    path.push(provinceNode.id)
    currentList = provinceNode.children || []

    // 查找城市
    if (city) {
      const cityNode = currentList.find((item: any) => item.name === city)
      if (cityNode) {
        path.push(cityNode.id)
        currentList = cityNode.children || []

        // 查找区县
        if (district) {
          const districtNode = currentList.find((item: any) => item.name === district)
          if (districtNode) {
            path.push(districtNode.id)
            currentList = districtNode.children || []

            // 查找乡镇
            if (town) {
              const townNode = currentList.find((item: any) => item.name === town)
              if (townNode) {
                path.push(townNode.id)
              }
            }
          }
        }
      }
    }
  }

  areaPath.value = path
}

/** 地图位置改变事件 */
const handleLocationChange = (lnglat: string[]) => {
  if (lnglat && lnglat.length === 2) {
    formData.value.longitude = parseFloat(lnglat[0])
    formData.value.latitude = parseFloat(lnglat[1])
  }
}

/** 根据地址定位地图 */
const locateByAddress = () => {
  // 构建完整地址
  const addressParts = [
    formData.value.province,
    formData.value.city,
    formData.value.district,
    formData.value.town,
    formData.value.detailAddress
  ].filter(Boolean) // 过滤掉空值

  const fullAddress = addressParts.join('')

  if (!fullAddress) {
    message.warning('请先选择地址信息')
    return
  }

  message.info(`正在定位：${fullAddress}`)

  // 如果地图组件已经加载，可以通过地图API进行地址解析
  // 这里我们构造一个提示，让用户在地图搜索框中输入
  nextTick(() => {
    // 这里可以调用地图组件的搜索功能
    console.log('定位地址:', fullAddress)
  })
}
</script>
